//
//  payView.m
//  BeautyPicture
//
//  Created by 沈振邦 on 15/12/7.
//  Copyright © 2015年 szb. All rights reserved.
//

#import "payView.h"
#import "headPromptView.h"
#import "AccountTool.h"
#import "Pingpp.h"
#import "BPhttpTool.h"
#include <sys/socket.h> // Per msqr
#include <sys/sysctl.h>
#include <net/if.h>
#include <net/if_dl.h>
#import "BPNavButtonView.h"
#import "AppDelegate.h"
#import "PayOverSuccessViewController.h"

#define kUrl  @"http://ttmy.len.so/app/order/tobepay" // 你的服务端创建并返回 charge 的 URL 地址。
#define kWaiting          @"正在获取支付凭据,请稍后..."
#define kNote             @"提示"
#define kConfirm          @"确定"
#define kErrorNet         @"网络错误"
#define kResult           @"支付结果：%@"

#define kPlaceHolder      @"支付金额"
#define kMaxAmount        9999999

#define kUrlScheme      @"BeautyPicture1" // 这个是你定义的 URL Scheme，支付宝、微信支付和测试模式需要。

@implementation payView



- (id)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        [self setUpView];
        UIView *naView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, BPScreenW, BPScreenNavY)];
        naView.backgroundColor = [UIColor whiteColor];
        [self addSubview:naView];
        
        BPNavButtonView *button = [[BPNavButtonView alloc] init];
        [button setTitleEdgeInsets:UIEdgeInsetsMake(0, 5, 0, 0)];
        [button setImageEdgeInsets:UIEdgeInsetsMake(0, 0, 0, 0)];
        [button setTitle:@"返回" forState:UIControlStateNormal];
        button.frame = CGRectMake(15, 16.0, 80, BPScreenNavY - 16.0);
        [naView addSubview:button];
        [button addTarget:self action:@selector(dismissView) forControlEvents:UIControlEventTouchUpInside];
        
        UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 16.0, 100, BPScreenNavY - 16.0)];
        titleLabel.center = CGPointMake(BPScreenW / 2.0, titleLabel.height / 2.0 + 16.0);
        titleLabel.text = @"支付";
        titleLabel.textColor = BPFenHongColor;
        titleLabel.textAlignment = NSTextAlignmentCenter;
        titleLabel.font = [UIFont boldSystemFontOfSize:20.0f];
        [naView addSubview:titleLabel];
        
        
        
        UIImageView *image = [[UIImageView alloc] initWithFrame:CGRectMake(0, 64, self.frame.size.width, 5)];
        image.image = [UIImage imageNamed:@"波纹线"];
        [naView addSubview:image];
    }
    return self;
}

- (void)dismissView{
    if ([D_Main_Appdelegate defeatView] != nil) {
        [[D_Main_Appdelegate defeatView] setHidden:YES];
        [D_Main_Appdelegate hideDefeatView];
    }
    [D_Main_Appdelegate hidePayView];
    
}

- (void)setUpView {
    
    //    [self setupNav];
    headView = [[headPromptView alloc] initWithFrame:CGRectMake(0, BPScreenNavY + 30.0, BPScreenW, 100)];
    [self addSubview:headView];
    
    self.backgroundColor = [UIColor whiteColor];
    
    CGFloat labelY = CGRectGetMaxY(headView.frame) + 40.0f;
    UILabel * promptLabel = [[UILabel alloc] init];
    promptLabel.font = [UIFont systemFontOfSize:15.0f];
    [self addSubview:promptLabel];
   // promptLabel.size = [self withLabel:promptLabel addText:[AccountTool account].mobile];
    promptLabel.centerX = BPScreenW / 2.0;
    promptLabel.centerY = labelY + promptLabel.height / 2.0;
    promptLabel.textAlignment = NSTextAlignmentCenter;
    
    
    
    
    _zhifuBao = [[UIButton alloc] initWithFrame:CGRectMake(0, 70, self.frame.size.width, 60)];
    _zhifuBao.tag = 2;
    [_zhifuBao addTarget:self action:@selector(normalPayAction:) forControlEvents:UIControlEventTouchUpInside];
    _zhifuBao.backgroundColor = [UIColor clearColor];
    [self addSubview:_zhifuBao];
    
    
    //设置按钮
    CGFloat btnH = 33.0f;
    CGFloat btnW = 110;
//    CGFloat btnY = CGRectGetMaxY(promptLabel.frame) + 50;
    UIButton *ZFBPayBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    ZFBPayBtn.size = CGSizeMake(btnW, btnH);
//    ZFBPayBtn.center = CGPointMake(BPScreenW / 2.0, btnY);
    ZFBPayBtn.frame = CGRectMake(70, 10, 100, 40);
    [ZFBPayBtn addTarget:self action:@selector(normalPayAction:) forControlEvents:UIControlEventTouchUpInside];
    [ZFBPayBtn setTag:2];
    [ZFBPayBtn setTitle:@"微信支付" forState:UIControlStateNormal];
//    [self setButton:ZFBPayBtn addButtonTitle:@"支付宝支付"];
    [ZFBPayBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    //[ZFBPayBtn setBackgroundColor:pinkBtnColor];
    [_zhifuBao addSubview:ZFBPayBtn];
    
    UIImageView *imageWx = [[UIImageView alloc] initWithFrame:CGRectMake(10, 10, 50, 40)];
    [imageWx setImage:[UIImage imageNamed:@"weiXinPay"]];
    [_zhifuBao addSubview:imageWx];
    
    
    // 中间的线
    UILabel *l = [[UILabel alloc] initWithFrame:CGRectMake(0, 60, self.frame.size.width, 1)];
    l.backgroundColor = [UIColor grayColor];
    l.alpha = 0.5;
    [_zhifuBao addSubview:l];
    
    
    
    UIButton *Weixin = [[UIButton alloc] initWithFrame:CGRectMake(0, 130, self.frame.size.width, 60)];
    Weixin.backgroundColor = [UIColor clearColor];
    [Weixin addTarget:self action:@selector(normalPayAction:) forControlEvents:UIControlEventTouchUpInside];
    Weixin.tag = 1;
    [self addSubview:Weixin];
    
//    CGFloat btnY2 = CGRectGetMaxY(ZFBPayBtn.frame) + 50;
    UIButton *WXPayBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    WXPayBtn.size = CGSizeMake(btnW, btnH);
//    WXPayBtn.center = CGPointMake(BPScreenW / 2.0, btnY2);
    WXPayBtn.frame = CGRectMake(75, 10, 100, 40);
    [WXPayBtn addTarget:self action:@selector(normalPayAction:) forControlEvents:UIControlEventTouchUpInside];
    [WXPayBtn setTag:1];
    [WXPayBtn setTitle:@"支付宝支付" forState:UIControlStateNormal];
    [Weixin addSubview:WXPayBtn];
//    [self setButton:WXPayBtn addButtonTitle:@"微信支付"];
//    [WXPayBtn setBackgroundColor:BPGlobaThemeColor];
    [WXPayBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    
    
    UIImageView *imageZFB = [[UIImageView alloc] initWithFrame:CGRectMake(10, 10, 50, 40)];
    [imageZFB setImage:[UIImage imageNamed:@"zhifuBaoPay"]];
    [Weixin addSubview:imageZFB];
    
    
    // 中间的线
    UILabel *la = [[UILabel alloc] initWithFrame:CGRectMake(0, 60, self.frame.size.width, 1)];
    la.backgroundColor = [UIColor grayColor];
    la.alpha = 0.5;
    [Weixin addSubview:la];

    
}

//- (void)setUpHeadView:(NSString *)orderId{
//    //设置头部提示view
//    [headView setUpPromptView:@"orderSuccess" and:@"嘻嘻~下单成功" withDetailInfo:orderId];
//}

//- (CGSize)withLabel:(UILabel *)textLabel addText:(NSString *)text
//{
//    textLabel.numberOfLines = 0;
//    NSMutableAttributedString *attStr = [[NSMutableAttributedString alloc]initWithString:[NSString stringWithFormat:@"进入'个人中心'并点戳\n【我的订单】\n随时掌控订单状态\n登录手机号为:%@",text]];
//    NSRange contentRange = {[attStr length] - [text length],[text length]};
//    [attStr addAttribute:NSForegroundColorAttributeName value:BPGlobaThemeColor range:contentRange];
//    NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc]init];
//    //设置行距
//    [style setLineSpacing:10.0f];
//    [style setAlignment:NSTextAlignmentCenter];
//    //判断内容长度是否大于Label内容宽度，如果不大于，则设置内容宽度为行宽（内容如果小于行宽，Label长度太短，如果Label有背景颜色，将影响布局效果）
//    NSInteger leng = textLabel.width;
//    if (attStr.length < textLabel.width) {
//        leng = attStr.length;
//    }
//    //根据给定长度与style设置attStr式样
//    [attStr addAttribute:NSParagraphStyleAttributeName value:style range:NSMakeRange(0, leng)];
//    //Label获取attStr式样
//    textLabel.attributedText = attStr;
//    //Label自适应大小
//    [textLabel sizeToFit];
//    //设置Label高度
//    return textLabel.frame.size;
//}

- (void)setButton:(UIButton *)button addButtonTitle:(NSString *)title
{
    [button.layer setMasksToBounds:YES];
    [button.layer setCornerRadius:15.0f];
    [button setTitle:title forState:UIControlStateNormal];
    [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [self addSubview:button];
}

- (void)normalPayAction:(id)sender
{
    NSInteger tag = ((UIButton*)sender).tag;
    if (tag == 1) {
        self.channel = @"alipay";
//        [self postMyServer];
    } else if (tag == 2) {
        self.channel = @"wx";
    } else if (tag == 3) {
        self.channel = @"upacp";
    } else if (tag == 4) {
        self.channel = @"bfb";
    } else {
        return;
    }
    NSLog(@"%@", [NSString stringWithFormat:@"%.0f",[self.price floatValue]*100]);
    
    NSDictionary* dict = @{
                           @"channel" : self.channel,
                           @"amount"  : [NSString stringWithFormat:@"%.0f",[self.price floatValue]*100],
                           @"orderid" : self.orderNumber,
                           @"subject" : @"天天美印作品",
                           @"body"    : @"天天美印作品",
                           };
    [BPhttpTool post:kUrl params:dict success:^(id responseObj) {
        
        self.Danhao = [responseObj objectForKey:@"order_no"];
        [Pingpp createPayment:responseObj appURLScheme:kUrlScheme withCompletion:^(NSString *result, PingppError *error) {            
            NSLog(@"completion block: %@", result);
            
            if (error == nil) {
                NSLog(@"PingppError is nil");
            } else {
                NSLog(@"PingppError: code=%lu msg=%@", (unsigned  long)error.code, [error getMsg]);
            }
            if (error.code == 5) {
                [self showAlertMessage:@"已取消付款"];
            }
            if ([result isEqualToString:@"success"]) {
                [self showAlertMessage:@"付款成功"];
                [D_Main_Appdelegate hidePayView];
                _block();
            }
            
        }];
    } failure:^(NSError *error) {
        BPLog(@"失败了? = %@",error);
    }];
}

- (void)showAlertWait
{
    mAlert = [[UIAlertView alloc] initWithTitle:kWaiting message:nil delegate:self cancelButtonTitle:nil otherButtonTitles: nil];
    [mAlert show];
    UIActivityIndicatorView* aiv = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite];
    aiv.center = CGPointMake(mAlert.frame.size.width / 2.0f - 15, mAlert.frame.size.height / 2.0f + 10 );
    [aiv startAnimating];
    [mAlert addSubview:aiv];
}

- (void)showAlertMessage:(NSString*)msg
{
    mAlert = [[UIAlertView alloc] initWithTitle:kNote message:msg delegate:nil cancelButtonTitle:kConfirm otherButtonTitles:nil, nil];
    [mAlert show];
}

- (void)hideAlert
{
    if (mAlert != nil)
    {
        [mAlert dismissWithClickedButtonIndex:0 animated:YES];
        mAlert = nil;
    }
}

@end
